package com.thl.filechooser;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mycp.videocompress.view.ClearEditText;
import com.xzkj.rx.thread.utils.Rx;
import com.xzkj.sp.SpUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class FileChooserActivity extends AppCompatActivity {

    private boolean showFile = true;
    private boolean showHideFile = true;
    private boolean showExternalSdCard = false;
    public static FileChooser mFileChooser;
    private String mChoosenFilePath;
    private String chooseType;

    private FileTourController tourController;
    private FileAdapter adapter;
    private CurrentFileAdapter currentFileAdapter;


    private RecyclerView fileRv;
    private ClearEditText searchEt;
    private TextView tvTitle;
    private ImageView more;
    private int firstItemPosition = 0;
    private int lastItemPosition = 0;
    private HashMap<Integer, Integer> firstItemPositionMap;
    private HashMap<Integer, Integer> lastItemPositionMap;
    private HashMap<String, Integer> positionMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_chooser);
        initListener();
    }

    private void initListener() {
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.rightText).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickRightText();
            }
        });


        this.showFile = getIntent().getBooleanExtra("showFile", true);
        this.showHideFile = getIntent().getBooleanExtra("showHideFile", true);
        this.showExternalSdCard = getIntent().getBooleanExtra("showExternalSdCard", false);
        this.mChoosenFilePath = getIntent().getStringExtra("currentPath");
        String title = getIntent().getStringExtra("title");
        int backIconRes = getIntent().getIntExtra("backIconRes", -1);
        int chooseCount = getIntent().getIntExtra("chooseCount", 1);
        chooseType = getIntent().getStringExtra("chooseType");
        int themeColorRes = getIntent().getIntExtra("themeColorRes", -1);

        tourController = new FileTourController(this, mChoosenFilePath, chooseType, showHideFile, showFile, showExternalSdCard);
        tourController.setShowHideFile(this.showHideFile);
        ImageView back = (ImageView) findViewById(R.id.back);
        tvTitle = (TextView) findViewById(R.id.title);
        searchEt = (ClearEditText) findViewById(R.id.searchEt);
        more = (ImageView) findViewById(R.id.more);
        View bgView = (View) findViewById(R.id.bg_title);
        if (backIconRes != -1) {
            back.setImageResource(backIconRes);
        }
        tvTitle.setText(title);
        if (themeColorRes != -1) {
            bgView.setBackgroundResource(themeColorRes);
        }
        findViewById(R.id.search).setOnClickListener(v -> {
            tvTitle.setVisibility(View.GONE);
            searchEt.setVisibility(View.VISIBLE);
            Rx.runUiDelay(() -> {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                searchEt.requestFocus();
                imm.showSoftInput(searchEt, InputMethodManager.SHOW_IMPLICIT);
            }, 200);
        });

        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    adapter.setData(tourController.getCurrenFileInfoList());
                    adapter.notifyData();
                } else {
                    adapter.setData(FileChooserListUtils.INSTANCE.getListByAllKey(adapter.dataList, s.toString()));
                    adapter.notifyData();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        adapter = new FileAdapter(this, (ArrayList<FileInfo>) tourController.getCurrenFileInfoList(), R.layout.item_file, chooseType, chooseCount, new SelectAllListener() {
            @Override
            public void onSelectAll() {
            }
        });
        fileRv = findViewById(R.id.fileRv);
        fileRv.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        fileRv.setAdapter(adapter);
//        fileRv.setVerticalScrollBarEnabled(true);
//        fileRv.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);

//        Drawable scrollbarTrackDrawable = ContextCompat.getDrawable(this, R.drawable.scroll_thumb); // 根据需要替换 R.drawable.scrollbar_vertical_track
//        Drawable scrollbarThumbDrawable = ContextCompat.getDrawable(this, R.drawable.scroll_thumb); // 根据需要替换 R.drawable.scrollbar_vertical_thumb
//        fileRv.setVerticalScrollBarEnabled(true);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
////            fileRv.setVerticalScrollbarTrackDrawable(scrollbarTrackDrawable);
//            fileRv.setVerticalScrollbarThumbDrawable(scrollbarThumbDrawable);
//        }
//
//        fileRv.setNestedScrollingEnabled(true);
        final RecyclerView currentPath = (RecyclerView) findViewById(R.id.currentPath);
        currentFileAdapter = new CurrentFileAdapter(this, (ArrayList<File>) tourController.getCurrentFolderList(), R.layout.item_current_file);
        currentPath.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        currentPath.setAdapter(currentFileAdapter);
        currentPath.scrollToPosition(tourController.getCurrentFolderList().size() - 1);
        firstItemPositionMap = new HashMap<>();
        lastItemPositionMap = new HashMap<>();

        fileRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//                if (recyclerView.getLayoutManager() != null && layoutManager instanceof LinearLayoutManager) {
//                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
//                    firstItemPosition = linearManager.findFirstVisibleItemPosition();
//                    lastItemPosition = linearManager.findLastVisibleItemPosition();
//                }

                // 滑动停止了，执行所需的操作
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    firstItemPosition = linearManager.findFirstVisibleItemPosition();
                    lastItemPosition = linearManager.findLastVisibleItemPosition();
                }
            }
        });

        adapter.setItemClickListener(new FileAdapter.ItemClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemClick(View view, int position, FileInfo data) {
                Rx.loopMsg(() -> {
                    File selectFile = new File(tourController.getCurrenFileInfoList().get(position).getFilePath());
                    if (selectFile.isDirectory()) {
                        ArrayList<FileInfo> childFileInfoList = (ArrayList<FileInfo>) tourController.addCurrentFile(selectFile);
                        Rx.runUi(() -> {
                            adapter.setData(childFileInfoList);
                            adapter.notifyData();
                            currentFileAdapter.setData(tourController.getCurrentFolderList());
                            currentFileAdapter.notifyDataSetChanged();

                            int sign = tourController.getCurrentFolderList().size() - 1;
                            currentPath.scrollToPosition(sign);
                            firstItemPositionMap.put(sign, firstItemPosition);
                            lastItemPositionMap.put(sign, lastItemPosition);
                        });
                    } else {
                        Rx.runUi(() -> adapter.notifyClick(data, position));
                    }
                    EventBus.getDefault().post(data);
                });

            }
        });

        currentFileAdapter.setItemClickListener(new CommonAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                List<FileInfo> fileInfoList = tourController.resetCurrentFile(position);
                adapter.setData(fileInfoList);
                adapter.notifyData();

                currentFileAdapter.setData(tourController.getCurrentFolderList());
                currentFileAdapter.notifyDataSetChanged();

                currentPath.scrollToPosition(tourController.getCurrentFolderList().size() - 1);
            }
        });

        findViewById(R.id.switchSdcard).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final ListPopupWindow listPopupWindow = new ListPopupWindow(FileChooserActivity.this);
                listPopupWindow.setAnchorView(v);
                ArrayList<String> sdcardList = new ArrayList<>();
                sdcardList.add("手机存储");
//                if (FileTourController.getStoragePath(FileChooserActivity.this, true) != null)
//                    sdcardList.add("SD卡");

                SdCardAdapter sdCardAdapter = new SdCardAdapter(FileChooserActivity.this, sdcardList);
                listPopupWindow.setAdapter(sdCardAdapter);
                listPopupWindow.setWidth(sdCardAdapter.getItemViewWidth());
                listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        firstItemPositionMap.clear();
                        lastItemPositionMap.clear();
                        firstItemPosition = 0;
                        lastItemPosition = 0;
                        if (tourController != null)
                            tourController.switchSdCard(position);
                        if (adapter != null) {
                            adapter.setData(tourController.getCurrenFileInfoList());
                            adapter.notifyDataSetChanged();
                        }
                        if (currentFileAdapter != null) {
                            currentFileAdapter.setData(tourController.getCurrentFolderList());
                            currentFileAdapter.notifyDataSetChanged();
                        }
                        listPopupWindow.dismiss();
                    }
                });
                listPopupWindow.show();

            }
        });

        more.setOnClickListener(v -> {
            List<String> items = Arrays.asList(
                    "排序",
                    "全选",
                    "取消全选",
                    "区间选择",
                    "扫描进媒体库",
                    "回到顶部",
                    "回到底部",
                    "所有文件可选",
                    "书签",
                    "收藏该路径"
            );
            FileChooserListUtils.INSTANCE.showListDialog(this, "操作", items, (index, content) -> {
                switch (index) {
                    case 0:
                        showSortDialog();
                        break;
                    case 1:
                        selectAll(true);
                        break;
                    case 2:
                        selectAll(false);
                        break;
                    case 3:
                        adapter.intervalSelectAll();
                        break;
                    case 4:
                        Rx.loopMsg(() -> {
                            for (String s : adapter.selectMap.keySet()) {
                                FileChooserListUtils.INSTANCE.scanFileToMediaStore(s, FileChooserActivity.this);
                            }
                            Rx.runUi(() -> Toast.makeText(FileChooserActivity.this,"成功扫描进媒体库",Toast.LENGTH_LONG).show());
                        });
                        break;
                    case 5:
                        fileRv.scrollToPosition(0);
                        break;
                    case 6:
                        fileRv.scrollToPosition(adapter.getItemCount()-1);
                        break;
                    case 7:
                        adapter.setAllFileAllowSelect(true);
                        tourController.setAllFileAllowSelect(true);
                        Rx.loopMsg(() -> {
                            if (tourController.getCurrentFile().isDirectory()) {
                                ArrayList<FileInfo> childFileInfoList = (ArrayList<FileInfo>) tourController.addCurrentFile(tourController.getCurrentFile());
                                Rx.runUi(() -> {
                                    adapter.setData(childFileInfoList);
                                    adapter.notifyData();
                                });
                            }
                        });
                        break;
                    case 8:
                        String pathList = SpUtils.get(this,"path_list","");
                        Type type = new TypeToken<List<PathItem>>(){}.getType();
                        List<PathItem> pathItems = new Gson().fromJson(pathList,type);
                        List<String> pathListItem = new ArrayList<>();
                        for (PathItem pathItem : pathItems) {
                            pathListItem.add(pathItem.getFilePath());
                        }
                        FileChooserListUtils.INSTANCE.showListDialog(this, "书签", pathListItem, new FileChooserListUtils.DialogListCall() {
                            @Override
                            public void listCall(int index, @Nullable String content) {

                                File selectFile = new File(content);
                                if (selectFile.isDirectory()) {
                                    ArrayList<FileInfo> childFileInfoList = (ArrayList<FileInfo>) tourController.addCurrentFile(selectFile);
                                    Rx.runUi(() -> {
                                        adapter.setData(childFileInfoList);
                                        adapter.notifyData();
                                        currentFileAdapter.setData(tourController.getCurrentFolderList());
                                        currentFileAdapter.notifyDataSetChanged();

                                        int sign = tourController.getCurrentFolderList().size() - 1;
                                        currentPath.scrollToPosition(sign);
                                        firstItemPositionMap.put(sign, firstItemPosition);
                                        lastItemPositionMap.put(sign, lastItemPosition);
                                    });
                                }
                            }
                        });
                        break;
                    case 9:
                        String starPath = tourController.getCurrentFile().getAbsolutePath();
                        PathItem item = new PathItem();
                        item.setPathMark("");
                        item.setFilePath(starPath);


                        String pathList2 = SpUtils.get(this,"path_list","");
                        Type type2 = new TypeToken<List<PathItem>>(){}.getType();
                        List<PathItem> pathItems2 = new Gson().fromJson(pathList2,type2);
                        if (null == pathItems2){
                            pathItems2 = new ArrayList<>();
                        }
                        for (PathItem pathItem : pathItems2) {
                            if (pathItem.equals(item.getFilePath())){
                                return;
                            }
                        }
                        pathItems2.add(item);
                        SpUtils.put(this,"path_list",new Gson().toJson(pathItems2));
                        break;
                }
            });
        });
    }

    public void showSortDialog() {
        List<String> items = Arrays.asList(
                "按名称(从A-Z)",
                "按名称(从Z-A)",
                "按日期(从新到旧)",
                "按日期(从旧到新)",
                "按大小(从大到小)",
                "按大小(从小到大)"
        );
        FileChooserListUtils.INSTANCE.showSingleCheckListDialog(this, SpUtils.get(this, "file_chooser_sort_index", 0), items, (index, content) -> {
            SpUtils.put(this, "file_chooser_sort_index", index);
            List<FileInfo> list = FileChooserListUtils.INSTANCE.getListSortByIndex(this, adapter.dataList);
            adapter.setData(list);
            adapter.notifyData();
        });
    }

    public void selectAll(boolean isChecked) {
        if (chooseType.equals(FileInfo.FILE_TYPE_FILE)) {
            //选择文件
            if (FileChooserListUtils.INSTANCE.getFileSize(adapter.dataList) == 0) {
                //没有可选文件，不可以全选
                return;
            }
        } else if (chooseType.equals(FileInfo.FILE_TYPE_FOLDER)) {
            //选择文件夹
            if (FileChooserListUtils.INSTANCE.getFolderSize(adapter.dataList) == 0) {
                //没有可选文件夹，不可以全选
                return;
            }
        }
        adapter.selectAllNotifyAllData(isChecked);
    }

    public void clickRightText() {
        if (adapter != null && adapter.getSize() <= 0) {
            Toast.makeText(this, "请选择文件路径", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tourController != null) {
            mChoosenFilePath = tourController.getCurrentFile().getAbsolutePath();
        }
        if (this.mFileChooser != null) {
            mFileChooser.finish(adapter.getChooseFilePath());
        }
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mFileChooser = null;
    }

    @Override
    public void onBackPressed() {
        if (searchEt.isShown()) {
            tvTitle.setVisibility(View.VISIBLE);
            searchEt.setVisibility(View.GONE);
            return;
        }
        if (!tourController.isRootFile()) {
            List<FileInfo> currentList = tourController.backToParent();
            adapter.setData(currentList);
            adapter.notifyDataSetChanged();
            currentFileAdapter.setData(tourController.getCurrentFolderList());
            currentFileAdapter.notifyDataSetChanged();

            int sign = tourController.getCurrentFolderList().size();
            Integer firstposition = firstItemPositionMap.get(sign);
            int first = firstposition == null ? 0 : firstposition.intValue();

            Integer lastItemPosition = lastItemPositionMap.get(sign);
            int last = lastItemPosition == null ? 0 : lastItemPosition.intValue();

            if (fileRv.getLayoutManager() != null) {
                ((LinearLayoutManager) fileRv.getLayoutManager()).scrollToPositionWithOffset(first, last);
            }
        } else {
            super.onBackPressed();
        }
    }

    public int dp2px(float dpValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    public interface SelectAllListener {
        void onSelectAll();
    }


}
